#!/usr/bin/env ruby

require 'rubygems'
require 'socket'
require File.expand_path(File.dirname(__FILE__) + "/../lib/epic.rb")
require File.expand_path(File.dirname(__FILE__) + "/../lib/epic/client.rb")

users = []
[when_ready,subscription,status,disconnected,disco_info].each {|m| m.clear}

when_ready { puts "connected! send messages to #{jid}" }
disconnected { puts "disconnecting!" }

subscription :request? do |s| 
	write_to_stream s.approve!
end 


status do |m| 
	puts "#{m.from}: #{m.state}"
	users << m.from if not users.include? m.from and m.from != jid.to_s
	users.delete(m.from) if m.status == :unavailable
end

disco_info do |m| 
	## api should be m.identities << getIdentity; write m.reply!
	id = Blather::Stanza::Disco::DiscoInfo::Identity.new(jid.node,"node","epic")
	stanza = Blather::Stanza::Disco::DiscoInfo.new(:result,nil,[id])
	stanza.id = m.id
	stanza.to = m.from
	stanza.from = m.to
	puts m
	puts stanza
	write_to_stream stanza
end

def set_subject
	throw Exception if jid.node != 'admin'
	debug 0
	client.write_with_handler(get_cmd) do |m| 
		m.reply!
		m.type = :set
		m.find("//ns:x", :ns => 'jabber:x:data').first['type'] = "submit"
		m.find("//ns:field[@var='subject']", :ns => 'jabber:x:data').first << Nokogiri::XML('<value>good news everyone</value>').root
		m.find("//ns:field[@var='body']", :ns => 'jabber:x:data').first << Nokogiri::XML('<value>we got control</value>').root
		write_to_stream m
	end
	debug 1
end

## located that command via using #info and #items queries on the server
def get_cmd
	ns = 'http://jabber.org/protocol/commands'
	node = 'http://jabber.org/protocol/admin#announce'
	action = 'execute'
	cmd = Blather::Stanza::Iq.new :set, Socket.gethostname
	cmd << Nokogiri::XML("<command xmlns='#{ns}' node='#{node}' action='#{action}'/>").root
	cmd
end

def start(user='echo')
	users = []
	setup "#{user}@#{Socket.gethostname}", user if user
	Thread.new { EM.run { client.run }} if not EM.reactor_running?
end

def debug(level=0)
	Blather.logger.level = level
end

def running?
	EM.reactor_running?
end

def stop
	EM.stop
end

def load
	source 'simple.rb'
end


